package com.cl.utils;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Component
public class SaveFile {
    public String savefile(CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        if(file==null){
            return "error";
        }else {
            String uploadFileName=file.getOriginalFilename();
            String path = request.getSession().getServletContext().getRealPath("/upload");
            File realPath = new File(path);
            if(!realPath.exists()){
                realPath.mkdir();
            }
            //将文件写出到本地
            InputStream is = file.getInputStream(); //文件输入流
            OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
            //将文件读取写出到本地
            int len=0;
            byte[] buffer = new byte[1024];
            while ((len=is.read(buffer))!=-1){
                os.write(buffer,0,len);
                os.flush();
            }
            os.close();
            is.close();
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            Upload bean = context.getBean("upload", Upload.class);
            String uploadUrl = bean.upload(realPath.getPath() + "\\" + uploadFileName, uploadFileName);
            File file1 = new File(realPath.getPath() + "\\" + uploadFileName);
            return uploadUrl;
        }

    }
}
